package com.heima.esdata;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.esdata.mapper.ApArticleContentMapper;
import com.heima.esdata.mapper.ApArticleMapper;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @作者 itcast
 * @创建日期 2021/2/22 9:15
 **/
@SpringBootTest
@RunWith(SpringRunner.class)
public class ImportArticleData {
    @Autowired
    ApArticleMapper apArticleMapper;
    @Autowired
    ApArticleContentMapper apArticleContentMapper;
    @Autowired
    RestHighLevelClient restHighLevelClient;


    @Test
    public void importData() throws IOException {
        String indexName = "app_info_article";
        // 1. 判断指定的索引库是否存在
        boolean hasIndex = existsIndex(indexName);
        // 2. 存在 删除该索引库
        if(hasIndex){
            deleteIndex(indexName);
        }
        // 3. 创建索引库
        createIndex("{\n" +
                "        \"properties\":{\n" +
                "            \"id\":{\n" +
                "                \"type\":\"keyword\"\n" +
                "            },\n" +
                "            \"publishTime\":{\n" +
                "                \"type\":\"date\"\n" +
                "            },\n" +
                "            \"layout\":{\n" +
                "                \"type\":\"short\"\n" +
                "            },\n" +
                "            \"images\":{\n" +
                "                \"type\":\"keyword\"\n" +
                "            },\n" +
                "            \"authorId\": {\n" +
                "          \t\t\"type\": \"integer\"\n" +
                "       \t\t},\n" +
                "            \"title\":{\n" +
                "                \"type\":\"text\",\n" +
                "                \"analyzer\":\"ik_smart\"\n" +
                "            },\n" +
                "            \"content\":{\n" +
                "                \"type\":\"text\",\n" +
                "                \"analyzer\":\"ik_smart\"\n" +
                "            }\n" +
                "        }\n" +
                "    }",indexName);
        // 4. 查询文章数据 每一个文章关联的内容数据
        // 得到所有符合条件的文章数据
        List<ApArticle> apArticles = apArticleMapper.loadArticleList();

        BulkRequest bulkRequest = new BulkRequest(indexName);
        for (ApArticle apArticle : apArticles) {


            ApArticleContent content = apArticleContentMapper.selectOne(
                    Wrappers.<ApArticleContent>lambdaQuery()
                            .eq(ApArticleContent::getArticleId, apArticle.getId())
            );
            // 封装文章数据
            Map<String,Object> map = new HashMap<>();
            map.put("id", String.valueOf(apArticle.getId()));
            map.put("publishTime", apArticle.getPublishTime());
            map.put("layout", apArticle.getLayout());
            map.put("images", apArticle.getImages());
            map.put("authorId", apArticle.getAuthorId());
            map.put("title", apArticle.getTitle());
            map.put("content", content.getContent());
            IndexRequest request = new IndexRequest();
            // 设置索引库中文章的文档ID
            request.id(String.valueOf(apArticle.getId()));
            request.source(map);
            bulkRequest.add(request);
        }
        // 5. 使用es的批处理功能 批量导入索引库
        restHighLevelClient.bulk(bulkRequest,RequestOptions.DEFAULT);
    }

    private void createIndex(String mappings, String indexName) throws IOException {
        CreateIndexRequest request = new CreateIndexRequest(indexName);
        request.mapping(mappings, XContentType.JSON);
        restHighLevelClient.indices().create(request,RequestOptions.DEFAULT);
    }

    /**
     * 删除索引库
     * @param indexName
     * @throws IOException
     */
    private void deleteIndex(String indexName) throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest(indexName);
        restHighLevelClient.indices().delete(request,RequestOptions.DEFAULT);
    }

    /**
     * 判断索引库是否存在
     * @param indexName
     * @return
     * @throws IOException
     */
    private boolean existsIndex(String indexName) throws IOException {
        GetIndexRequest request = new GetIndexRequest(indexName);
        return restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
    }
}
